
var fs = require('fs');
var url = require('url');
var cheerio = require('cheerio')
var request = require('request')


getUrl('http://www.mm131.com/xinggan/2234.html',data=>{
	 console.log(data)
	var $ = cheerio.load(data);

	// console.log($('img').length)
	$('img').each(function(i,e){
		if($(this).attr('src')){
			let title=$(this).attr('src');
			console.log(title,i)
		// console.log($(this).attr('src'),i)
				request($(this).attr('src')).pipe(fs.createWriteStream(i+'.jpg'))
		}
		// request($(this).attr('src')).pipe(fs.createWriteStream(i+'.jpg'))
		// var contentText = fs.readFileSync('123.txt','utf-8');
		// fs.writeFile(e,$(this).attr('src'))
		// if($(this).attr('src').charAt(0)=='h'){
		// 	console.log('true')
		// }
			// request($(this).attr('src')).pipe(fs.createWriteStream(i+'.jpg'))
	})
	// fs.writeFile('tupian.jpg',data)
})
function getUrl(sUrl,success){
var urlObj = url.parse(sUrl);
var http='';
if(urlObj=='http:'){
	 http = require('http')
}else{
	 http = require('https')
}
console.log(urlObj,urlObj.hostname,urlObj.path,'????????')
let req = http.request({
	'hostname':urlObj.hostname,
	// 'path':urlObj.path
},res=>{
	console.log(res.statusCode,'ggggg')
	if(res.statusCode==200){
		var arr =[];
	var str = '';
	res.on('data',buffer=>{
		arr.push(buffer);
		str+=buffer;
	});
	res.on('end',()=>{
		let b = Buffer.concat(arr);
		success&&success(str)

	})
}else if(res.statusCode=='302'||res.statusCode=='301'){
	console.log('what???')
	getUrl(res.headers.location,success)
}
});
req.end();
req.on('error',(e)=>{
	console.log(e.message)
})
}






// var kk = http.request({
// 	'hostname':'nodejs.cn',
// 	'path':'/download/'
// },(res)=>{
// 	var str = '';
// 	res.on('data',buffer=>{
// 		str+=buffer;
// 		console.log(str)
// 	});
// 	res.on('end',()=>{
// 		fs.writeFile('dwonload.html',str,'utf-8')
// 	})
// })
// kk.end();
